<?php
Core::getInstance()->sys_load_class('Mysql',false);
Core::getInstance()->sys_load_class('Xml',false);
class Model{
	public $_table = '';
	public $_mdb = null;
	public $_qdb = null;
	public $_item=10;

	public function __construct($db='default'){
		$xml = WEB_ROOT.'config.xml';
		$config = Xml::parse($xml,'db',$db);

		$this->_mdb = new Mysql(); // 用于更新插入删除

		$main = $config['main']['value'];
		$m_config = explode('|',$main);

		$this->_mdb->connect($m_config[0],$m_config[2],$m_config[3],$m_config[1]);


		$this->_qdb = new Mysql(); // 用于查询
		$query = $config['query']['value'];
		$q_config = explode('|',$query);
		$this->_qdb->connect($q_config[0],$q_config[2],$q_config[3],$q_config[1]);
	}

	public function query($sql,$db=true){
		if($db){
			$this->_mdb->query($sql);
		}else{
			$this->_qdb->query($sql);
		}
	}
	
	public function add($data){
		$key = implode(',',array_keys($data));
		$values = implode(',',$data);
		$sql = "INSERT INTO {$this->_table}({$key}) VALUES({$values})";
		$this->_mdb->query($sql);
		return $this->_mdb->insert_id();
	}

	public function update($data,$where='',$format=true){
		$set = '';
		foreach($data as $k=>$v){
			$set .= $format?"`$k`='$v',":"$k=$v,";
		}
		$set = substr($set,0,-1);
		$sql = "UPDATE {$this->_table} SET $set";
		if($where) $sql = $sql.' WHERE '.$where;

		$this->_mdb->query($sql);
		return $this->_mdb->insert_id();
	}


	public function getOne($sql){
		return $this->_qdb->fetch_first($sql);
	}

	public function lists(){
		$item=$this->_item; // 每页显示的条数
		$page = isset($_GET['page'])?intval($_GET['page']):0;
		$sql = "select * from {$this->_table} limit ".($item*$page).",".$item;
		$query = $this->_qdb->query($sql);
		$data = array();
		while($r = $this->_qdb->fetch_array($query)){
			$data[] = $r;
		}

		return $data;
	}

	public function getAll(){
		$sql = "select * from {$this->_table} order by id desc";
		$query = $this->_qdb->query($sql);
		$data = array();
		while($r = $this->_qdb->fetch_array($query)){
			$data[] = $r;
		}

		return $data;
	}

	public function page(){
		$num = $this->getOne("select count(*) as num from {$this->_table}");
		$num = $num['num'];
		Core::getInstance()->sys_load_class('Page',false);
		$page = new Page($num,$this->_item);
		return $page->render();
		
	}

	public function del($id){
		$sql="delete from {$this->_table} WHERE id=".intval($id);
		$this->_mdb->query($sql);
	}

	// 获得所有的数据
	public function all($sql){
		$query = $this->_qdb->query($sql);
		$data = array();
		while($r = $this->_qdb->fetch_array($query)){
			$data[] = $r;
		}
		return $data;
	}


}
